(function () {
    "use strict";

    var url,
        $successMessage,
        $errorMessage;

    url = 'http://localhost:3000/students';
    $successMessage = $('.messages .success');
    $errorMessage = $('.messages .error');

    function visualizeStudents() {
        $.ajax({
            url: url,
            type: 'GET',
            contentType: 'application/json',
            timeout: 5000,
            success: function (data) {
                var len,
                    i,
                    student,
                    $studentsList;

                $studentsList = $('<ul />');

                for (i = 0, len = data.students.length; i < len; i++) {
                    student = data.students[i];

                    $('<li />')
                        .append(student.id + '. ' + student.name + ', grade: ' + student.grade)
                        .appendTo($studentsList);
                }

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2000);

                $('#students-container').html($studentsList);
            },
            error: function (error) {
                $errorMessage
                    .html('Error: ' + error)
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function addStudent(student) {
        return $.ajax({
            url: url,
            type: 'POST',
            data: JSON.stringify(student),
            contentType: 'application/json',
            timeout: 5000,
            success: function () {
                visualizeStudents();
            },
            error: function (error) {
                $errorMessage
                    .html('Error: ' + error)
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function deleteStudent(id) {
        var studentUrl = url + '/' + id + '/';

        $.ajax({
            url: studentUrl,
            type: 'POST',
            timeout: 5000,
            data: {_method: 'delete'},
            success: function () {
                visualizeStudents();
            },
            error: function (error) {
                $errorMessage
                    .html('Error: ' + error)
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    (function($) {
        visualizeStudents();

        $('#button-add').on('click', function () {
            var student;

            student = {
                name: $('#input-name').val(),
                grade: $('#input-grade').val()
            };

            addStudent(student);
        });

        $('#button-delete').on('click', function () {
            var id;

            id = $('#input-id').val();

            deleteStudent(id);
        });
    }(jQuery));
}());